﻿using Api.Application.Command.UserRole;
using Api.DTO;
using AutoMapper;
using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;

namespace Api.Application.Handler.UserRole
{
    public class GetUserRoleHandler : IRequestHandler<GetUserRoleCommand, ApiResult<List<UserRoleDTO>>>
    {
        private readonly IBase<UserRoleModel> userRoleRepo;
        private readonly IBase<UserModel> userRepo;
        private readonly IMapper mapper;

        public GetUserRoleHandler(IBase<UserRoleModel> userRoleRepo,IBase<UserModel> userRepo,IMapper mapper)
        {
            this.userRoleRepo = userRoleRepo;
            this.userRepo = userRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<List<UserRoleDTO>>> Handle(GetUserRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<UserRoleDTO>> result = new ApiResult<List<UserRoleDTO>>();
            var user = userRoleRepo.GetAll().Where(x => x.RoleId == request.RoleId).Select(x => x.UserId);
            var userlist = userRepo.GetAll().Where(x =>user.Contains(x.Id));
            var model   =mapper.Map<List<UserRoleDTO>>(userlist);

            result.Code = ApiEnum.OK;
            result.Data = model;
            result.Msg = "显示成功";
            return Task.FromResult(result);
        }
    }
}
